<template>
  <div class="fullheight">
    <el-dialog
      fullscreen
      top="6vh"
      :title="formData.xqmc + '自动排课'"
      class="sp-manager__dialog"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      :before-close="beforeCloseDialog"
      append-to-body
      :close-on-click-modal="false"
      v-loading.fullscreen.lock="loading"
      element-loading-text="加载中..."
      center
    >
      <el-steps :active="active" simple>
        <el-step
          v-for="item in stepList"
          :key="item.key"
          :title="item.value"
          :status="getStepStatus(item.key)"
          :icon="getIconClass(item.key)"
        >
        </el-step>
      </el-steps>
      <div class="main-content">
        <!-- 排课属性设置 -->
        <CoursePropertySetting
          v-if="active == 1"
          ref="coursePropertySetting"
          :editId="editId"
          :editData.sync="formData"
        ></CoursePropertySetting>
        <!-- 排课规则 -->
        <CourseRule
          v-if="active == 2"
          ref="courseRule"
          :editId="editId"
          :editData="formData"
        ></CourseRule>
        <!-- 教室 -->
        <Classroom
          v-if="active == 3"
          ref="classroom"
          :editId="editId"
        ></Classroom>
        <!-- 任务书 -->
        <TaskBook v-if="active == 4" ref="taskBook" :editId="editId"></TaskBook>
        <!-- 自动排课进度 -->
        <AutoCourseProcess
          v-if="active == 5"
          ref="autoCourseProcess"
          :editData="formData"
        ></AutoCourseProcess>
        <!-- 排课预览 -->
        <CoursePreview
          v-if="active == 6"
          ref="coursePreview"
          :editId="editId"
          :editData="formData"
        ></CoursePreview>
      </div>

      <div class="bottom-btn" style="margin-top:50px">
        <el-button @click="lastStep" :disabled="lastDisabled">上一步</el-button>
        <el-button @click="nextSetp" :disabled="nextDisabled" v-if="isShowNext"
          >{{this.active != 5? '下一步': '查看排课结果' }}</el-button
        >
        <el-button
          @click="abandonWrite"
          type="primary"
          v-if="active == 6"
          >重新排课</el-button
        >
        <el-button
          @click="startLesson"
          type="primary"
          v-if="
            active == 5 &&
            formData.pkzt != '1'
          "
          >{{ formData.pkzt === '0' ? '开始排课' : '重新排课' }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import course from '@/api/course.js'

import CoursePropertySetting from '@/views/course/record/component/CoursePropertySetting.vue'
import CourseRule from '@/views/course/record/component/CourseRule.vue'
import Classroom from '@/views/course/record/component/Classroom.vue'
import TaskBook from '@/views/course/record/component/TaskBook.vue'
import AutoCourseProcess from '@/views/course/record/component/AutoCourseProcess.vue'
import CoursePreview from '@/views/course/record/component/CoursePreview.vue'

export default {
  components: {
    CoursePropertySetting,
    CourseRule,
    Classroom,
    TaskBook,
    AutoCourseProcess,
    CoursePreview
  },
  data() {
    return {
      loading: false,
      editId: '', // 编辑id 存在说明是编辑
      dialogVisible: false,
      formData: {
        xqmc: '', // 学期名称
        xqid: '', // 学期id
        pksx: '' // 排课属性
      },
      saveMethod: 'POST',
      active: 0,
      stepList: [
        {key: 1, value: '排课属性设置'},
        {key: 2, value: '排课规则'},
        {key: 3, value: '教室'},
        {key: 4, value: '任务书'},
        {key: 5, value: '自动排课进度'},
        {key: 6, value: '排课结果'}
      ]
    }
  },
  computed: {
    isShowNext() {
      if (this.active == 6) {
        return false
      }
      if (
        this.active == 5 &&
        (!this.formData.pkzt || this.formData.pkzt == '0')
      ) {
        return false
      }
      return true
    },
    nextDisabled() {
      if (this.active >= 6) {
        return true
      } else {
        return false
      }
    },
    lastDisabled() {
      if (this.active <= 1) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    // 放弃写入
    abandonWrite() {
        this.$confirm(
            '重新排课后此次排课结果不予保留，是否选择重新排课？',
            '提示信息',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            this.loading = true
            course.abandonWrite(this.editId).then(
                res => {
                    this.loading = false
                    if (res.state) {
                        this.$message.success(res.message || '操作成功！')
                        this.getDetailData()
                        this.$emit('updateTable')
                        this.active = 1
                    } else {
                        this.$message.error(res.message || '操作失败!')
                    }
                },
                err => {
                    this.loading = false
                }
            )
        })

    },
    // 写入课表
    writeLesson() {
      this.loading = true
      course
        .writeLesson(this.editId, this.$refs.coursePreview.search.type)
        .then(
          res => {
            this.loading = false
            if (res.state) {
              this.$message.success(res.message || '操作成功！')
              this.getDetailData()
              this.$emit('updateTable')
            } else {
              this.$message.error(res.message || '操作失败!')
            }
          },
          err => {
            this.loading = false
          }
        )
    },
    // 开始排课
    startLesson() {
      this.$confirm(
        '是否确定开始排课？排课的具体完成情况请查看排课日志。',
        '提示信息',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.loading = true
        course.startLesson(this.editId).then(
          res => {
            this.loading = false
            if (res && res.state) {
                this.$message.success('排课成功！')
                this.$emit('updateTable')
                this.getDetailData()
            }else {
                this.$message.error(res.message || '接口异常！')
            }

          },
          err => {
            this.loading = false
          }
        )
      })
    },
    async nextSetp() {
      if (this.formData.pkzt && this.formData.pkzt != '0') {
        this.active++
        return
      }
      // 点击下一步时，需保存当前页数据，然后再进行下一步
      if (this.active == 1) {
        let result = await this.$refs.coursePropertySetting.validateData()
        if (result === false) {
          return
        }
        this.formData.xqmc = result.xqmc
        this.formData.xqid = result.xqid
        this.formData.pksx = result.pksx
      }
      if (this.active == 2) {
        this.formData.ruleList = JSON.parse(
          JSON.stringify(this.$refs.courseRule.selectedData)
        )
      }
      if (this.active == 3) {
        if (
          !this.$refs.classroom.tableData ||
          !this.$refs.classroom.tableData.length
        ) {
          this.$confirm('未选择教室会默认选择全部教室，是否继续?', '提示信息', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.active++
          })
          return
        }
      }
      if (this.active == 4) {
        if (
          !this.$refs.taskBook.tableData ||
          !this.$refs.taskBook.tableData.length
        ) {
          this.$confirm(
            '未选择任务书会默认选择全部任务书，是否继续?',
            '提示信息',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            this.active++
          })
          return
        }
      }
      if (
        this.active != 3 &&
        this.active != 4 &&
        this.active != 5 &&
        this.formData.pkzt != '2' &&
        this.formData.pkzt != '1'
      ) {
        let resultFlag = await this.saveData()
        if (resultFlag === false) {
          this.$message.error('保存失败！')
          return
        }
      }
      this.active++
    },
    // 保存数据
    saveData() {
      return new Promise(resolve => {
        course.saveSemesterData(this.formData).then(res => {
          if (res.state) {
            if (!this.editId) {
              // 如果是新增 保存后 重新获取 编辑数据
              this.editId = res.value
              this.getDetailData()
              this.$emit('updateTable')
            }
            resolve()
          } else {
            resolve(false)
          }
        })
      })
    },
    // 获取编辑详情
    getDetailData(type) {
      this.loading = true
      course.getSemesterDetail(this.editId).then(
        res => {
          this.loading = false
          if (res.state) {
            this.formData = res.value
            if (type == 'init') {
              this.active = 1
            }
          } else {
            this.$message.error(res.message || '接口异常！')
          }
        },
        err => {
          this.loading = false
        }
      )
    },
    lastStep() {
      this.active--
    },
    getStepStatus(index) {
      if (this.active > index) {
        return 'finish'
      } else if (this.active == index) {
        return 'wait'
      } else {
        return 'process'
      }
    },
    getIconClass(index) {
      if (this.active > index) {
        return 'el-icon-success'
      } else if (this.active == index) {
        return 'el-icon-time'
      } else {
        return 'el-icon-remove'
      }
    },
    showDialog(id) {
      this.active = 0
      if (id) {
        this.editId = id
        this.getDetailData('init')
        this.dialogVisible = true
      } else {
        this.editId = ''
        this.active = 1
        this.formData = {}
        this.dialogVisible = true
      }
    },
    beforeCloseDialog() {
      this.formData = {}
      this.dialogVisible = false
    },
    // saveData() {
    //   let _this = this
    //   this.$validator.validateAll('recordManagerForm').then(result => {
    //     if (result) {
    //     } else {
    //       let arr = this.$validator.errors.items.filter(
    //         item => item.scope == 'recordManagerForm'
    //       )
    //       let errorLength = arr.length
    //       this.$message({
    //         showClose: true,
    //         message: `有${errorLength}个字段未通过校验，请正确填写表单内容。`,
    //         type: 'warning'
    //       })
    //     }
    //   })
    // },
    afterSaveData() {
      setTimeout(() => {
        this.beforeCloseDialog()
        this.$parent && this.$parent.loadData({})
      }, 500)
    }
  }
}
</script>
<style lang="scss" scoped>
.sp-manager__dialog ::v-deep .el-dialog > .el-dialog__body {
  height: calc(100% - 170px);
  padding-top: 0;
}
.bottom-btn {
  text-align: center;
}
.main-content {
  height: calc(100% - 200px);
  overflow-y: auto;
}
</style>
